import { useLoading } from '@hooks/useLoading';
import MsgModel from '@model/MsgModel';
import { connectorFormSettingInterfaceList } from '@src/api/ConnectorApi';
import { ConnectorOptionsAction } from '@src/modules/connector';
import { covertSetForDataKey } from '@src/modules/connector/util/convert';
import Log from '@src/util/log';
import { message } from '@src/util/message';
import { Ref, ref } from 'vue';


export function useConnectorCardSettingFetchInterfaceList() {
  // 加载状态
  const { loading, setLoading, clearLoading } = useLoading();

  // 模块App列表
  const interfaceList: Ref<ConnectorOptionsAction[]> = ref([]);

  const fetchInterFaceList = (params = {}) => {
    setLoading();

    const covertInterfaceResultData = (result: ConnectorOptionsAction []) => {

      return result.map((item: ConnectorOptionsAction)=> {

        item = covertSetForDataKey(item, ['toResponseFieldList', 'toResponseFieldList'], ['supportSelect', 'supportSelect'])
        return item
      })
    }

    return connectorFormSettingInterfaceList(params)
      .then(result => {
        if (MsgModel.isSuccess(result)) {
          interfaceList.value = covertInterfaceResultData(result?.data || []);
        } else {
          interfaceList.value = []
          message.error(result?.message);
        }

        return interfaceList.value;
      })
      .catch(error => {
        Log.error(error, fetchInterFaceList.name);

        return [] as any[];
      })
      .finally(() => {
        clearLoading();
      });
  };

  return {
    fetchInterFaceList,
    interfaceList,
    loading,
  };
}
